package com.ultrasoft.farmasoft.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.ultrasoft.farmasoft.domain.Attribute;


@Transactional(readOnly = false)
@Repository(value = "attributeDao")
public class AttributeDaoImpl implements AttributeDao {
	private EntityManager em = null;
    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
    
    @SuppressWarnings("unchecked")
	public List<Attribute> getAttribute() {
		return em.createNamedQuery("Attribute.findAll").getResultList();
	}
	@SuppressWarnings("unchecked")
	public List<Attribute> getAttributeListByActiveSubstanceId(Integer idActiveSubstance){
		Query  q = em.createNamedQuery("Attribute.findByActiveSubstanceId");
    	//q.setParameter("countryId",idCountry);
    	q.setParameter("activeSubstanceId",idActiveSubstance);
    	//q.setParameter("active",active);
    	return q.getResultList();
	}
	
	public Attribute findAttributeByIDActiveSubstanceAndIDAttribute(Integer idAttribute, Integer idActiveSubstance) {
		Attribute res=null;
    	Query  q = em.createNamedQuery("Attribute.findByAttributeIdByActiveSubstanceId");
    	q.setParameter("attributeId",idAttribute);
    	q.setParameter("activeSubstanceId",idActiveSubstance);
    	if(q.getResultList().size()==1)
    		res=(Attribute)q.getSingleResult();
    	return res;
	}

	public Attribute findAttributeByID(Integer idAttribute) {
		Attribute res=null;
    	Query  q = em.createNamedQuery("Attribute.findByAttributeId");
    	q.setParameter("attributeId",idAttribute);
    	
    	if(q.getResultList().size()==1)
    		res=(Attribute)q.getSingleResult();
    	return res;
	}
	
	
	
	
	public void add(Attribute attribute){
		em.persist(attribute);
	}
	public void update(Attribute attribute) {
		em.merge(attribute);
	}
/*
	public void remove(Attribute attribute) {
		Query q = em.createNamedQuery("Attribute.deleteByAttributeId");
    	q.executeUpdate();
	}
	*/
	public void remove(Attribute attribute) {
		Query q = em.createNamedQuery("Attribute.deleteByActiveSubstanceIdByAttributeId");
    	q.setParameter("activeSubstanceId",attribute.getAttributePK().getActiveSubstanceId());
    	q.setParameter("attributeId",attribute.getAttributePK().getAttributeId());
    	q.executeUpdate();
		//em.remove(city);
	}
	
	public Integer getAttributeId(){
		Integer res = 0;
		res=(Integer)em.createNamedQuery("Attribute.findByAttributeIdMax").getSingleResult();
		if(res != null){
			res++;
		}else{
			res=1;
		}
		return res;
	}
}
